package com.andaily.web.controller.validator;

import com.andaily.domain.dto.user.RegisterUserDTO;
import com.andaily.domain.shared.MatchUtils;
import com.andaily.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * @author Shengzhao Li
 */
public class RegisterUserValidator implements Validator {

    private UserService userService;

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz.equals(RegisterUserDTO.class);
    }

    @Override
    public void validate(Object target, Errors errors) {
        RegisterUserDTO registerUserDTO = (RegisterUserDTO) target;

        validateEmail(errors, registerUserDTO);
        validatePassword(errors, registerUserDTO);
        validateCellPhone(errors, registerUserDTO);
    }

    private void validateCellPhone(Errors errors, RegisterUserDTO registerUserDTO) {
        String cellPhone = registerUserDTO.getCellPhone();
        if (StringUtils.isEmpty(cellPhone)) {
            return;
        }
        boolean isNumber = MatchUtils.isPositiveNumber(cellPhone);
        if (!isNumber) {
            errors.rejectValue("cellPhone", null, "手机必须是数字");
        }

    }

    private void validatePassword(Errors errors, RegisterUserDTO registerUserDTO) {
        String password = registerUserDTO.getPassword();
        if (StringUtils.isBlank(password)) {
            errors.rejectValue("password", null, "密码不能为空");
        } else {
            if (password.length() < 8) {
                errors.rejectValue("password", null, "密码至少8位");
            }
        }

        String rePassword = registerUserDTO.getRePassword();
        if (StringUtils.isBlank(rePassword)) {
            errors.rejectValue("rePassword", null, "确认密码不能为空");
        } else {
            if (!password.equals(rePassword)) {
                errors.rejectValue("rePassword", null, "两次输入的密码不一致");
            }
        }

    }

    private void validateEmail(Errors errors, RegisterUserDTO registerUserDTO) {
        String email = registerUserDTO.getEmail();
        if (StringUtils.isBlank(email)) {
            errors.rejectValue("email", null, "邮箱不能为空");
        } else {
            boolean isEmail = MatchUtils.isEmail(email);
            if (isEmail) {
                String userGuid = userService.loadUserGuidByEmail(email);
                if (userGuid != null) {
                    errors.rejectValue("email", null, "该邮箱已被注册");
                }
            } else {
                errors.rejectValue("email", null, "邮箱格式错误");
            }
        }

    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
